package com.example.dreamlist2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;

public class LoginActivity extends AppCompatActivity {
    private Button log_cancel;
    private Button log;
    private User user;
    StateInfo stateInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        stateInfo = (StateInfo)getApplication();
        log = findViewById(R.id.login);
        log_cancel = findViewById(R.id.login_cancel);

        user = new User();

        log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

        log_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void login(){
        EditText uid = findViewById(R.id.uid);
        EditText password = findViewById(R.id.password);

        String id = uid.getText().toString();
        String pswd = password.getText().toString();

        BmobQuery<User> query = new BmobQuery<User>();
        query.getObject(id, new QueryListener<User>() {
            @Override
            public void done(User u, BmobException e) {
                if(e==null){
                    if(pswd.equals(u.getPassword())){
                        user = u;//设置用户
                        stateInfo.setLogin(true);
                        stateInfo.setUserin(user);
                        //进入主页
                        //todo:确定需要的传参
                        //Utils.launch(LoginActivity.this, BaseActivity.class, bundle, null);
                        Intent intent = new Intent(LoginActivity.this, BaseActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    else{
                        user = null;
                        stateInfo.setLogin(false);
                        Toast.makeText(getApplicationContext(), "密码错误！", Toast.LENGTH_LONG).show();
                        refresh();
                    }
                }else{
                    user = null;
                    stateInfo.setLogin(false);
                    Log.i("bmob","失败："+e.getMessage()+","+e.getErrorCode());
                    Toast.makeText(getApplicationContext(), "登陆失败！", Toast.LENGTH_LONG).show();
                    refresh();
                }
            }
        });

    }

    //用于刷新
    public void refresh(){
        onCreate(null);
    }

}